#include "StackNQueue.h"
STACK S;
QUEUE Q;
int extractStack = FALSE, extractQueue = FALSE;
void pushStack(int x, STACK *S)
{
    STACK_NODE *tmp;
    tmp = (STACK_NODE *)malloc(sizeof(STACK_NODE));
    tmp -> number = x;
    tmp -> prev = NULL;
    tmp -> next = NULL;
    if(S -> last != NULL)
    {
        tmp -> prev = S -> last;
        S -> last -> next = tmp;
        S -> last = tmp;
    }
    else
        S -> first = S -> last = tmp;
    extractStack = TRUE;
}
void printStack(STACK S)
{
    printf("Printed stack: ");
    STACK_NODE *tmp = S.first;
    if(tmp == NULL)
        printf("Stack is empty.");
    else
        for(; tmp != NULL; tmp = tmp -> next)
            printf("%d ", tmp -> number);
}
int popStack(STACK *S)
{
    int info = S -> last -> number;
    STACK_NODE *tmp = S -> last;
    if (tmp -> prev == NULL)
    {
        S -> last = NULL;
        S -> first = NULL;
        extractStack = FALSE;
    }
    else
    {
        tmp -> prev -> next = NULL;
        S -> last = tmp -> prev;
    }
    free(tmp);
    return info;
}
void pushQueue(int x, QUEUE *Q)
{
    QUEUE_NODE *tmp;
    tmp = (QUEUE_NODE *)malloc(sizeof(QUEUE_NODE));
    tmp -> number = x;
    tmp -> prev = NULL;
    tmp -> next = NULL;
    if(Q -> last != NULL)
    {
        tmp -> prev = Q -> last;
        Q -> last -> next = tmp;
        Q -> last = tmp;
    }
    else
        Q -> first = Q -> last = tmp;
    extractQueue = TRUE;
}
void printQueue(QUEUE Q)
{
    printf("Printed queue: ");
    QUEUE_NODE *tmp = Q.first;
    if(tmp == NULL)
        printf("Queue is empty.");
    else
        for(; tmp != NULL; tmp = tmp -> next)
            printf("%d ", tmp -> number);
}
int popQueue(QUEUE *Q)
{
    int info = Q -> first -> number;
    QUEUE_NODE *tmp = Q -> first;
    if (tmp -> next == NULL)
    {
        Q -> first = NULL;
        Q -> last = NULL;
        extractQueue = FALSE;
    }
    else
    {
        tmp -> next -> prev = NULL;
        Q -> first = tmp -> next;
    }
    free(tmp);
    return info;
}
void SolveProblem(int check)
{
    int i, v[] = {5, 4, 3, 2, 1}, x, found = FALSE;
    for (i = 0; i < 5; ++i)
        pushStack(v[i], &S);
    printStack(S);
    while (extractStack == TRUE)
    {
        x = popStack(&S);
        if (x == check)
            found = TRUE;
        pushQueue(x, &Q);
    }
    printf("\n%d\n", found);
    printQueue(Q);
    printf("\n");
    while (extractQueue == TRUE)
        pushStack(popQueue(&Q), &S);
    printStack(S);
    printf("\n");
    while (extractStack == TRUE)
        pushQueue(popStack(&S), &Q);
    printQueue(Q);
    printf("\n");
    while (extractQueue == TRUE)
        pushStack(popQueue(&Q), &S);
    printStack(S);
}

